package org.de.maeyer.unit;

/**
 * This abstract class provides common functionality applicable to all units.
 * <ul>
 * <li>Two units are equal if their names are equal (case sensitive).
 * <li>The hash code of a unit is based on its name.</li>
 * <li>Stringification of a unit returns its symbol.</li>
 * </ul>
 * 
 * @author Peter De Maeyer
 */
public abstract class AbstractUnit implements Unit {

	@Override
	public int hashCode() {
		return getName().hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!(obj instanceof AbstractUnit)) {
			return false;
		}
		return getName().equals(((AbstractUnit) obj).getName());
	}

	@Override
	public String toString() {
		return getSymbol();
	}

	double convertTo(double value, MultiplyingUnit unit) {
		throw newArithmeticException(this, unit);
	}

	double convertTo(double value, NonMultiplyingUnit unit) {
		throw newArithmeticException(this, unit);
	}

	ArithmeticException newArithmeticException(Unit expected, Unit actual) {
		return new ArithmeticException("units mismatch: " + expected + " != " + actual);
	}
}
